﻿using Ldt.DataEngine.DataFlowParse.Model;
using Ldt.DataEngine.RuleAssemble;
using LdtDataEngin.ModuleDetail.BaseModule;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.EvidenceQuestion;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.ModuleDetail
{
    public class EvidenceQuestion:AssermBase
    {
        /// <summary>
        /// 配置实体
        /// </summary>
        private EvidenceQusetionModel evidenceQusetionModel;

        /// <summary>
        ///声明证据与质证意见对应类
        /// </summary>
        /// <param name="configXml"></param>
        public EvidenceQuestion(DataContext dataContext,string moduleName)
        {
            base.dataContext = dataContext;
            base.MoudleName = moduleName;
        }

        /// <summary>
        /// 执行证据与质证意见关系解析
        /// </summary>
        public void Extract()
        {
            // 模块配置
            ConfigModel moudleConfig = dataContext.DataLayerSys.GetConfigModel(MoudleName);
            //证据与质证意见配置
            ConfigModel evidenceQuestionConfig = moudleConfig.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "evidexamsociety");
            //解析证据与质证意见配置
            evidenceQusetionModel = XmlUtility.DeserializeToObject<EvidenceQusetionModel>(evidenceQuestionConfig?.ConfigContent);
            Dictionary<string, List<FileName>> evidenceDic = EvidenceExtract();
            Dictionary<string, List<FileName>> questionDic = QuestionExtract();
            if (questionDic.Count > 0 && evidenceDic.Count > 0)
            {
                if (questionDic.Count == 1 && evidenceDic.Count == 1 && evidenceDic.FirstOrDefault().Key != questionDic.FirstOrDefault().Key &&
                    evidenceDic.FirstOrDefault().Value.Where(a => a.name == evidenceQusetionModel.ResultModel.evidenceID).ToList().Count == 1 &&
                    questionDic.FirstOrDefault().Value.Where(a => a.name == evidenceQusetionModel.ResultModel.questionID).ToList().Count == 1)
                {
                    IsEvidenctReg(evidenceDic.FirstOrDefault().Value, questionDic.FirstOrDefault().Value);
                }
                else
                {
                    foreach (var questionItem in questionDic)
                    {
                        var evideItemDic = evidenceDic.FirstOrDefault(a => a.Key != questionItem.Key);
                        if (evideItemDic.Key!=null)
                        {
                            if (questionItem.Value.FirstOrDefault(a => a.name.ToLower() == evidenceQusetionModel.ResultModel.quesetionText.ToLower())!=null)
                            {
                                List<FileName> quesetFileTextList = questionItem.Value.Where(a => a.name == evidenceQusetionModel.ResultModel.quesetionText).ToList();
                                foreach (FileName feileText in quesetFileTextList)
                                {
                                    List<string> numberList= RuleParseClass.GetParseRegCodeList(evidenceQusetionModel.ResultModel.quesetionBhReg, feileText.fileValue, null);
                                    if (numberList.Count>0)
                                    {
                                        string number = numberList[0];
                                        List<string> quesetionNumberList = new List<string>();
                                        if (number.IndexOf(",")>-1)
                                        {
                                            quesetionNumberList = number.Split(',').ToList();
                                        }
                                        else if (number.IndexOf("，")>-1)
                                        {
                                            quesetionNumberList = number.Split('，').ToList();
                                        }
                                        else if (number.IndexOf("、")>-1)
                                        {
                                            quesetionNumberList = number.Split('、').ToList();
                                        }
                                        else
                                        {
                                            quesetionNumberList.Add(number);
                                        }
                                        bool qusetTextIs = true;
                                        foreach (string qusetionNumber in quesetionNumberList)
                                        {
                                            if (evideItemDic.Value.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.evidenceNumber)!=null)
                                            {
                                                qusetTextIs = false;
                                                FileName evideitemNumber = evideItemDic.Value.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.evidenceNumber);
                                                if (questionItem.Value.FirstOrDefault(a => a.NodeID == feileText.NodeID || a.NodeID==feileText.ParentID)!=null)
                                                {
                                                    List<FileName> fileNameQuesetionList = questionItem.Value.Where(a => a.NodeID == feileText.NodeID || a.NodeID == feileText.ParentID).ToList();
                                                    List<FileName> fileNmaeEvidenList = evideItemDic.Value.Where(a => a.NodeID == evideitemNumber.ParentID || a.NodeID== evideitemNumber.NodeID).ToList();
                                                    IsEvidenctReg(fileNmaeEvidenList, fileNameQuesetionList);
                                                }
                                            }
                                        }
                                        if (qusetTextIs)
                                        {
                                            List<FileName> fileNameQuesetionList = questionItem.Value.Where(a => a.NodeID == feileText.ParentID || a.ParentID == feileText.NodeID).ToList();
                                            if (evideItemDic.Value.FirstOrDefault(a=> a.name==evidenceQusetionModel.ResultModel.evidenceID)!=null)
                                            {
                                                foreach (FileName evidenName in evideItemDic.Value.Where(a => a.name == evidenceQusetionModel.ResultModel.evidenceID))
                                                {
                                                    List<FileName> fileNmaeEvidenList = evideItemDic.Value.Where(a => a.NodeID == evidenName.ParentID || a.ParentID == evidenName.NodeID).ToList();
                                                    IsEvidenctReg(fileNmaeEvidenList, fileNameQuesetionList);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        List<FileName> fileNameQuesetionList = questionItem.Value.Where(a => a.NodeID == feileText.ParentID || a.NodeID == feileText.NodeID).ToList();
                                        if (evideItemDic.Value.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.evidenceID) != null)
                                        {
                                            foreach (FileName evidenName in evideItemDic.Value.Where(a => a.name == evidenceQusetionModel.ResultModel.evidenceID))
                                            {
                                                List<FileName> fileNmaeEvidenList = evideItemDic.Value.Where(a => a.NodeID == evidenName.ParentID || a.ParentID == evidenName.NodeID).ToList();
                                                IsEvidenctReg(fileNmaeEvidenList, fileNameQuesetionList);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                dataContext.DataLayerAns.AnalysisResultsXml = XmlUtility.DataModelByXml(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList);
            }
        }

        /// <summary>
        /// 计算是否添加质证意见关系
        /// </summary>
        /// <param name="evidenceList"></param>
        /// <param name="quesetionList"></param>
        public void IsEvidenctReg(List<FileName> evidenceList, List<FileName> quesetionList) 
        {
            string quesetext = quesetionList.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.quesetionText).fileValue;
            List<string> valueList = RuleParseClass.GetParseRegCodeList(evidenceQusetionModel.ResultModel.IsEvidenctReg, quesetext, null);
            if (valueList.Count > 0)
            {
                //匹配成功
                dataContext.InteractiveShow.LogShow("证据与质证意见匹配成功");
                //是否认定
                FileName fileNameEvide = evidenceList.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.IsCongizance);
                UpdateDataModel(fileNameEvide.NodeID, fileNameEvide.value, "1");
                //是否有质证意见
                FileName fileNameEviderd = evidenceList.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.IsQuesetion);
                UpdateDataModel(fileNameEviderd.NodeID, fileNameEviderd.value, "1");
            }
            else
            {
                dataContext.InteractiveShow.LogShow("证据与质证意见未匹配成功");
                AddNode(evidenceList, quesetionList);
                //是否认定
                FileName fileNameEvide = evidenceList.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.IsCongizance);
                if (fileNameEvide!=null)
                {
                    UpdateDataModel(fileNameEvide.NodeID, fileNameEvide.value, "2");
                    //是否有质证意见
                    FileName fileNameEviderd = evidenceList.FirstOrDefault(a => a.name == evidenceQusetionModel.ResultModel.IsQuesetion);
                    UpdateDataModel(fileNameEviderd.NodeID, fileNameEviderd.value, "0");
                }
            }
        }
  
        /// <summary>
        /// 没匹配上认定正则添加节点
        /// </summary>
        /// <param name="evidenceList"></param>
        /// <param name="quesetionList"></param>
        public void AddNode(List<FileName> evidenceList, List<FileName> quesetionList)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            string id = xmlUtilCommon.CaseNodeUpdate(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, evidenceQusetionModel.ResultModel.ResultXmlpath);
            
            XmlDocument xmlDocument = new XmlDocument();
            XmlElement oRootNode=xmlDocument.CreateElement("详情");
            xmlDocument.AppendChild(oRootNode);
            XmlElement xmlNode = (XmlElement)xmlDocument.SelectSingleNode("详情");
            var evidenceNameID = FileValue(evidenceList, evidenceQusetionModel.ResultModel.evidenceNameID);
            xmlNode.SetAttribute("证据名称ID", evidenceNameID);
            var evidenceID = FileValue(evidenceList, evidenceQusetionModel.ResultModel.evidenceID);
            xmlNode.SetAttribute("证据主张方ID", evidenceID);
            var quesetionR = FileValue(quesetionList, evidenceQusetionModel.ResultModel.quesetionR);
            xmlNode.SetAttribute("质证方ID", quesetionR);
            var questionID = FileValue(quesetionList, evidenceQusetionModel.ResultModel.questionID);
            xmlNode.SetAttribute("质证内容ID", questionID);
            DataSoursModel dataSoursModel = xmlUtilCommon.GetXMLByDataModelBackFill(xmlDocument);
            dataSoursModel.dataModelList.FirstOrDefault(a => a.ParentId == "").ParentId = id;
            dataContext.InteractiveShow.LogShow("添加的节点"+System.Environment.NewLine+JsonConvert.SerializeObject(dataSoursModel.dataModelList));
            dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.AddRange(dataSoursModel.dataModelList);
        }

        /// <summary>
        /// 获取集合体的值
        /// </summary>
        /// <param name="fileNameList"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string FileValue(List<FileName> fileNameList, string name)
        {
            string value = "";
            if (fileNameList.FirstOrDefault(a => a.name == name) != null)
            {
                value = fileNameList.FirstOrDefault(a => a.name == name).fileValue;
            }

            return value;

        }


        /// <summary>
        /// 更新分析数据
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="attName"></param>
        /// <param name="attValue"></param>
        public void UpdateDataModel(string nodeId,string attName,string attValue) 
        {
            attName = attName.Replace("@", "");
            DataModel dataModel= dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.FirstOrDefault(a => a.ID == nodeId);
            if (dataModel!=null)
            {
                var attmodel= dataModel.AttributesList.FirstOrDefault(a => a.Name == attName);
                if (attmodel!=null)
                {
                    attmodel.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = attValue;
                }
                else
                {
                    AttributeInfo attribute = new AttributeInfo();
                    attribute.Name = attName;
                    attribute.sourceList = new List<Source>();
                    Source source = new Source();
                    source.AnalysisStatus = "0";
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.IsCheck = "1";
                    source.SaveValue = attValue;
                    attribute.sourceList.Add(source);
                    dataModel.AttributesList.Add(attribute);
                }
            }
        
        }
        /// <summary>
        /// 获取证据对象
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, List<FileName>> EvidenceExtract()
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            EvidenceModel evidenceModel = evidenceQusetionModel.EvidenceModel;
            Dictionary<string, List<FileName>> evidenceDic = new Dictionary<string, List<FileName>>();
            List<DataModel> dataModels = XmlUtility.ConditionDataModelList(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList,"", evidenceModel.path);
            if (dataModels!=null && dataModels.Any())
            {
                List<DataModel> dataModelList = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList.Where(a => a.XmlPath == evidenceModel.path).ToList();
                foreach (DataModel dataModelRoot in dataModels)
                {
                    string name = GetAttValue(dataModelRoot, "主张方姓名");
                    string suitid = GetAttValue(dataModelRoot, "主张方诉讼地位");
                    foreach (FileName frileitem in evidenceModel.fileNameList)
                    {

                        frileitem.fileValue = GetAttValue(dataModelRoot, frileitem.value);
                        frileitem.NodeID = dataModelRoot.ID;
                        frileitem.ParentID = dataModelRoot.ID;
                        frileitem.xPath = dataModelRoot.XmlPath;
                        if (evidenceDic.ContainsKey(name+suitid))
                        {
                            List<FileName> fileNames = new List<FileName>();
                            var jsonStr = JsonConvert.SerializeObject(evidenceDic[name + suitid]);
                            fileNames = JsonConvert.DeserializeObject<List<FileName>>(jsonStr);
                            fileNames.Add(frileitem);
                            evidenceDic.Remove(name + suitid);
                            evidenceDic.Add(name + suitid, fileNames);
                        }
                        else
                        {
                            List<FileName> fileNameList = new List<FileName>();
                            fileNameList.Add(frileitem);
                            evidenceDic.Add(name + suitid, fileNameList);
                        }

                    }
                    List<DataModel> suberList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, dataModelRoot);
                    foreach (EvidenceModel evidenceNode in evidenceModel.evidenceModelList)
                    {
                        if (suberList.FirstOrDefault(a => a.XmlPath == dataModelRoot.XmlPath + evidenceNode.path ) != null)
                        {
                            List<DataModel> dataModeNodelList = suberList.Where(a => a.XmlPath == dataModelRoot.XmlPath + evidenceNode.path ).ToList();
                            foreach (DataModel dataModelNode in dataModeNodelList)
                            {
                                foreach (FileName frileitem in evidenceNode.fileNameList)
                                {
                                    frileitem.fileValue = GetAttValue(dataModelNode, frileitem.value);
                                    frileitem.NodeID = dataModelNode.ID;
                                    frileitem.ParentID = dataModelRoot.ID;
                                    frileitem.xPath = dataModelRoot.XmlPath + evidenceNode.path;
                                    if (evidenceDic.ContainsKey(name + suitid))
                                    {
                                        List<FileName> fileNames = new List<FileName>();
                                        var jsonStr = JsonConvert.SerializeObject(evidenceDic[name + suitid]);
                                        fileNames = JsonConvert.DeserializeObject<List<FileName>>(jsonStr);
                                        fileNames.Add(frileitem);
                                        evidenceDic.Remove(name + suitid);
                                        evidenceDic.Add(name + suitid, fileNames);
                                    }
                                    else
                                    {
                                        List<FileName> fileNameList = new List<FileName>();
                                        fileNameList.Add(frileitem);
                                        evidenceDic.Add(name + suitid, fileNameList);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            dataContext.InteractiveShow.LogShow("获取证据对象:"+JsonConvert.SerializeObject(evidenceDic));
            return evidenceDic;
        }

        /// <summary>
        /// 获取质证对象
        /// </summary>
        public Dictionary<string, List<FileName>> QuestionExtract()
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            QuestionModel questionModel = evidenceQusetionModel.QuestionModel;
            Dictionary<string, List<FileName>> questionDic = new Dictionary<string, List<FileName>>();
            List<DataModel> dataModels = XmlUtility.ConditionDataModelList(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "", questionModel.path);
            if (dataModels != null && dataModels.Any())
            {
                foreach (DataModel dataModelRoot in dataModels)
                {
                    string name = GetAttValue(dataModelRoot, "主张方姓名");
                    string suitid = GetAttValue(dataModelRoot, "主张方诉讼地位");

                    foreach (FileName frileitem in questionModel.fileNameList)
                    {
                        frileitem.fileValue = GetAttValue(dataModelRoot, frileitem.value);
                        frileitem.xPath = dataModelRoot.XmlPath;
                        frileitem.NodeID = dataModelRoot.ID;
                        frileitem.ParentID = dataModelRoot.ID;
                        if (questionDic.ContainsKey(name + suitid))
                        {
                            List<FileName> fileNames = new List<FileName>();
                            var jsonStr = JsonConvert.SerializeObject(questionDic[name + suitid]);
                            fileNames = JsonConvert.DeserializeObject<List<FileName>>(jsonStr);
                            fileNames.Add(frileitem);
                            questionDic.Remove(name + suitid);
                            questionDic.Add(name + suitid, fileNames);
                        }
                        else
                        {
                            List<FileName> fileNameList = new List<FileName>();
                            fileNameList.Add(frileitem);
                            questionDic.Add(name + suitid, fileNameList);
                        }
                    }
                    List<DataModel> suberList = xmlUtilCommon.SubordinateDataModelList(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, dataModelRoot);

                    foreach (QuestionModel questionNode in questionModel.questionModelList)
                    {
                        if (suberList.FirstOrDefault(a =>  a.XmlPath == dataModelRoot.XmlPath + questionNode.path ) != null)
                        {
                            List<DataModel> dataModeNodelList = suberList.Where(a => a.XmlPath == dataModelRoot.XmlPath + questionNode.path ).ToList();
                            foreach (DataModel dataModelNode in dataModeNodelList)
                            {
                                foreach (FileName frileitem in questionNode.fileNameList)
                                {
                                    frileitem.fileValue = GetAttValue(dataModelNode, frileitem.value);
                                    frileitem.NodeID = dataModelNode.ID;
                                    frileitem.xPath = dataModelRoot.XmlPath + questionNode.path;
                                    frileitem.ParentID = dataModelRoot.ID;
                                    if (questionDic.ContainsKey(name + suitid))
                                    {
                                        List<FileName> fileNames = new List<FileName>();
                                        var jsonStr = JsonConvert.SerializeObject(questionDic[name + suitid]);
                                        fileNames = JsonConvert.DeserializeObject<List<FileName>>(jsonStr);
                                        fileNames.Add(frileitem);
                                        questionDic.Remove(name + suitid);
                                        questionDic.Add(name + suitid, fileNames);
                                    }
                                    else
                                    {
                                        List<FileName> fileNameList = new List<FileName>();
                                        fileNameList.Add(frileitem);
                                        questionDic.Add(name + suitid, fileNameList);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            dataContext.InteractiveShow.LogShow("获取质证对象:" + JsonConvert.SerializeObject(questionDic));
            return questionDic;
        }

        /// <summary>
        /// 获取属性值
        /// </summary>
        /// <param name="dataModel">节点内容</param>
        /// <param name="dataModel">节点内容</param>
        /// <returns></returns>
        public string GetAttValue(DataModel dataModel, string attName)
        {
            attName = attName.Replace("@", "");
            string value = "";
            if (dataModel.AttributesList.FirstOrDefault(a => a.Name == attName) != null)
            {
                value = dataModel.AttributesList.FirstOrDefault(a => a.Name == attName).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                
            }
            if (attName.ToLower() == "id")
            {
                value = dataModel.ID;
            }
            return value;
        }
    }
}
